/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.dtgenerator.api.mgrInterface.method;

import com.inspur.edp.bef.bizentity.GspBizEntityObject;
import com.inspur.edp.bef.bizentity.GspBusinessEntity;
import com.inspur.edp.bef.bizentity.operation.BizMgrAction;
import com.inspur.edp.bef.bizentity.operation.BizOperation;
import com.inspur.edp.bef.bizentity.operation.collection.BizMgrActionCollection;
import com.inspur.edp.bef.dtgenerator.api.BefApiGeneratorContext;
import com.inspur.edp.caf.generator.BaseGenerator;
import java.util.ArrayList;

public class MgrMethodBuildUtil {

  public static void addBizActionGenerators(ArrayList<BaseGenerator> list,
      BefApiGeneratorContext apiGenContext) {
    BizMgrActionCollection actions = apiGenContext.getBeGenCtx().getBE().getCustomMgrActions();
    if(actions == null || actions.isEmpty()) {
      return;
    }
    list.ensureCapacity(actions.size());
    for(BizOperation action : actions) {
      list.add(new MgrInterfaceMethodGenerator((BizMgrAction) action, apiGenContext));
    }
  }

  public static void addDefaultActionGenerators(ArrayList<BaseGenerator> list,
      BefApiGeneratorContext apiGenContext) {
    for (GspBizEntityObject node : apiGenContext.getBeGenCtx().getBE().getAllNodes()) {
      if (node.getIsRootNode()) {
        continue;
      }
      checkChildActionCode(node, apiGenContext.getBeGenCtx().getBE());
      list.add(new MgrInterfaceDeleteGenerator(node));
      list.add(new MgrInterfaceRetrieveGenerator(node));
    }
  }

  private static void checkChildActionCode(GspBizEntityObject node, GspBusinessEntity be) {
    for (BizOperation bo : be.getBizMgrActions()) {
      String suffix = node.getCode();
      if (suffix.equals("Child")) {
        suffix = suffix + "Node";
      }
      boolean condition1 = bo.getCode().equals("Delete" + suffix);
      boolean condition2 = bo.getCode().equals("RetrieveDefault" + suffix);
      if (condition1 || condition2) {
        throw new RuntimeException(
            "自定义动作编号"
                + bo.getCode()
                + "与内置动作编号重复，请更换自定义动作编号。"
                + "BE编号:{apiGenContext.getBeGenCtx().BE.getCode()}；BE名称：{apiGenContext.getBeGenCtx().BE.Name},动作编号：{bo.getCode()}；动作名称：{bo.Name}；节点编号：{node.getCode()}；节点名称：{node.Name}。");
      }
    }
  }
}
